package com.help10000.rms.common

import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Handler
import android.os.Looper
import androidx.multidex.MultiDexApplication
import com.alibaba.sdk.android.push.CommonCallback
import com.alibaba.sdk.android.push.huawei.HuaWeiRegister
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory
import com.alibaba.sdk.android.push.register.MiPushRegister
import com.alibaba.sdk.android.push.register.OppoRegister
import com.alibaba.sdk.android.push.register.VivoRegister
import com.amir.common.utils.LogUtils
import com.help10000.rms.config.*
import com.help10000.rms.mvp.presenter.LocationPresenter
import com.help10000.rms.ui.utils.NetWorkUtil
import com.huawei.hms.aaid.HmsInstanceId
import com.mob.MobSDK
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.map.geolocation.TencentLocationManager
import java.util.concurrent.TimeUnit

class App {
    companion object {
        var isInit = false;
        var handler = Handler(Looper.getMainLooper());
        fun isInited(): Boolean {
            return isInit;
        }

        fun init(application: Application) {
            LogUtils.E("App init")
            this.isInit = true;
            CrashReport.initCrashReport(application.applicationContext);
            NetWorkUtil.init(application)
            MobSDK.submitPolicyGrantResult(true, null);
            TencentLocationManager.getInstance(application);
            initCloudChannel(application)
//            ExecutorServiceManager.SCHEDULE_THREAD_EXECUTOR.scheduleAtFixedRate(
//                {
//                    try { //每3分钟上报一次位置
//                        handler.post { LocationPresenter().reportLocation() };
//                    } catch (e: Exception) {
//                        LogUtils.E(e)
//                    }
//                },
//                2, 3, TimeUnit.MINUTES
//            )
            //启动推送服务
            var intent = Intent(application.applicationContext, PushServiceDeamon::class.java)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            application.applicationContext.startService(intent)
        }

        /**
         * 初始化阿里云云推送通道
         * @param applicationContext
         */
        private fun initCloudChannel(application: Application) {
            createNotificationChannel(application)
            PushServiceFactory.init(application)
            val pushService = PushServiceFactory.getCloudPushService()
            pushService.register(application, object : CommonCallback {
                override fun onSuccess(response: String?) {
                    LogUtils.E("init cloudchannel success")
                    LogUtils.E("deviceId：${pushService.deviceId}")
                    globalData.deviceId = pushService.deviceId

                }

                override fun onFailed(errorCode: String, errorMessage: String) {
                    LogUtils.E("init cloudchannel failed -- errorcode:$errorCode -- errorMessage:$errorMessage")
                }
            })

            MiPushRegister.register(application, XIAOMI_ID, XIAOMI_KEY); // 初始化小米辅助推送
            HuaWeiRegister.register(application); // 接入华为辅助推送
            VivoRegister.register(application); // 接入Vivo辅助推送
            OppoRegister.register(application, OPPO_KEY, OPPO_SECRET); // 接入Oppo辅助推送

         //  getToken(application)
        }

        private fun getToken(context: Context) {
            // 创建一个新线程
            object : Thread() {
                override fun run() {
                    try {
                        // 从agconnect-service.json文件中读取appId
                        val appId = "105006461"

                        // 输入token标识"HCM"
                        val tokenScope = "HCM"
                        val token =
                            HmsInstanceId.getInstance(context).getToken(appId, tokenScope)
                        LogUtils.E("get token:$token")


                    } catch (e: Exception) {

                    }
                }
            }.start()
        }

        private fun createNotificationChannel(context: Context) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val mNotificationManager =
                    context.getSystemService(MultiDexApplication.NOTIFICATION_SERVICE) as NotificationManager
                // 通知渠道的id
                val id = "10086"
                // 用户可以看到的通知渠道的名字.
                val name: CharSequence = "推送消息"
                // 用户可以看到的通知渠道的描述
                val description = "新消提醒"
                val importance = NotificationManager.IMPORTANCE_HIGH
                val mChannel = NotificationChannel(id, name, importance)
                // 配置通知渠道的属性
                mChannel.description = description
                // 设置通知出现时的闪灯（如果 android 设备支持的话）
                mChannel.enableLights(true)
                mChannel.lightColor = Color.RED
                // 设置通知出现时的震动（如果 android 设备支持的话）
                mChannel.enableVibration(true)
                //    mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
                //最后在notificationmanager中创建该通知渠道
                mNotificationManager.createNotificationChannel(mChannel)
            }
        }
    }
}